package com.lovecws.mumu.ffmpeg.video;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/5/17.
 * 获取视频的基本信息
 */
public class VideoInfoService {

    //视频路径
    private String ffmpegApp;

    public String getFfmpegApp() {
        return ffmpegApp;
    }

    public void setFfmpegApp(String ffmpegApp) {
        this.ffmpegApp = ffmpegApp;
    }

    public VideoInfoService(String ffmpegApp) {
        this.ffmpegApp = ffmpegApp;
    }

    /**
     * 获取视频的基本信息
     * @param videoFilename 视频文件路径
     * @throws IOException
     * @throws InterruptedException
     */
    public VideoInfo getInfo(String videoFilename) throws IOException,InterruptedException {
        VideoInfo videoInfo=new VideoInfo();
        String tmpFile = videoFilename + ".tmp.png";
        ProcessBuilder processBuilder = new ProcessBuilder(ffmpegApp, "-y",
                "-i", videoFilename, "-vframes", "1", "-ss", "0:0:0", "-an",
                "-vcodec", "png", "-f", "rawvideo", "-s", "100*100", tmpFile);

        Process process = processBuilder.start();

        InputStream stderr = process.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stderr);
        BufferedReader br = new BufferedReader(isr);
        String line;
        //打印 sb，获取更多信息。 如 bitrate、width、heigt
        StringBuffer sb = new StringBuffer();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        new File(tmpFile).delete();

        videoInfo.setMsg(sb.toString());
        Pattern pattern = Pattern.compile("Duration: (.*?),");
        Matcher matcher = pattern.matcher(sb);

        if (matcher.find()) {
            String time = matcher.group(1);
            calcTime(time,videoInfo);
        }

        pattern = Pattern.compile("w:\\d+ h:\\d+");
        matcher = pattern.matcher(sb);

        if (matcher.find()) {
            String wh = matcher.group();
            //w:100 h:100
            String[] strs = wh.split("\\s+");
            if (strs != null && strs.length == 2) {
                int width = Integer.parseInt(strs[0].split(":")[1]);
                int heigt = Integer.parseInt(strs[1].split(":")[1]);
                videoInfo.setWidth(width);
                videoInfo.setHeigt(heigt);
            }
        }
        process.waitFor();
        if (br != null)
            br.close();
        if (isr != null)
            isr.close();
        if (stderr != null)
            stderr.close();

        return videoInfo;
    }

    private void calcTime(String timeStr,VideoInfo videoInfo) {
        String[] parts = timeStr.split(":");
        int hours = Integer.parseInt(parts[0]);
        videoInfo.setHours(hours);
        int minutes = Integer.parseInt(parts[1]);
        videoInfo.setMinutes(minutes);
        float seconds = Float.parseFloat(parts[2]);
        videoInfo.setSeconds(seconds);
    }
}
